<?php

class Money_OrderController extends Core_Controller_Action_Standard {

    public function init() {
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer || !$viewer->getIdentity()) {
            return $this->_helper->redirector->gotoRoute(array(), 'default', true);
        }

        $type = $this->_getParam('type');
        $identity = $this->_getParam('id');
        if ($type && $identity) {
            $item = Engine_Api::_()->getItem($type, $identity);
            if ($item instanceof Core_Model_Item_Abstract) {
                if (!Engine_Api::_()->core()->hasSubject()) {
                    Engine_Api::_()->core()->setSubject($item);
                }
            }
        }

        $this->_helper->requireSubject();
    }

    function paidAction() {
        if (!$this->_helper->requireUser()->isValid())
            return;

        $this->view->money = $money = Engine_Api::_()->getDbtable('money', 'money')->getMoney();
        $this->view->item = $subject = Engine_Api::_()->core()->getSubject();

        if ($money < $subject->amount) {
            $this->_helper->redirector->gotoRoute(array('action' => 'recharge'));
        }

        $viewer = Engine_Api::_()->user()->getViewer();

        $this->view->form = $form = new Money_Form_Paid();

        if (!$this->getRequest()->isPost()) {
            return;
        }

        if (!$form->isValid($this->getRequest()->getPost())) {
            return;
        }

        $table = Engine_Api::_()->getDbtable('orders', 'money');

        $db = $table->getAdapter();
        $db->beginTransaction();
        try {
            $order = $table->setItem($subject, $viewer);

            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        $transactiontable = Engine_Api::_()->getDbtable('transactions', 'money');


        try {
            $transactiontable->createTransaction($order, $subject, $viewer);
        } catch (Money_Model_Exception $e) {
            
        }
         return $this->_forward('success', 'utility', 'core', array(
                    'messages' => array(Zend_Registry::get('Zend_Translate')->_('Course was created successfully')),
                    'redirect' => $this->_helper->redirector->gotoUrl($subject->getHref(), array('prependBase' => false))
                ));
        
    }

    function rechargeAction() {
        $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('money_main');
    }

}
